<template>
  <div class="app-container">

    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="8">
            <el-form-item label="关 键 字">
              <el-input style="width: 95%" v-model="searchObj.keyword" placeholder="姓名/身份证号/手机号/文件名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作时间">
              <el-date-picker
                v-model="createTimes"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="margin-right: 10px;width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" icon="el-icon-search" size="mini" :loading="loading" @click="searchData()">搜索</el-button>
          <el-button type="danger" v-if="$hasPermission('product:protr:delete')" class="btn-add" size="mini" @click="batchRemove()" >批量删除</el-button>
          <el-button type="success" size="mini"  @click="openDialog()">上传文件</el-button>
        </el-row>
        
      </el-form>
    </div>
    <br />
    
    <!-- 列表 -->
    <el-table

      v-loading="listLoading"
      :data="list"
      stripe
      border
      style="width: 100%;margin-top: 10px;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="userName" label="姓名" align="center"  />
      <el-table-column prop="idNumber" label="身份证号" align="center"  />
      <el-table-column prop="phoneNo" label="手机号" align="center" />
      <el-table-column prop="fileName" label="文件名" align="center"  />
      <el-table-column prop="type" label="文件类型" align="center"  />
      <el-table-column prop="createDate" label="创建时间" align="center" />

      <el-table-column label="操作" width="80" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除" />
        </template>
      </el-table-column>
    </el-table>
    

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center;"
      layout="sizes, prev, pager, next, jumper, ->, total, slot"
      @current-change="fetchData"
      @size-change="changeSize"
    />
 

    <el-dialog  :visible.sync="dialogVisible" title="上传文件" :close-on-click-modal="false" :close-on-press-escape="false">
          
        
        <el-form :model="fileMeta" :rules="rules" ref="fileMeta" label-width="100px" class="demo-ruleForm">
          <el-form-item label="操作" >
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="url"
              :file-list="fileList"
              :headers="headerData"
              :auto-upload="false"
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleChange"
              :before-upload="beforeUploadHandle"
              :on-success="successHandle"
         
              >
              <el-button  size="mini"  type="success" icon="el-icon-plus" >选取文件</el-button>
              <span style="margin-left: 30px;" class="el-upload__tip" slot="tip">文件命名示例:张三-410329000000000000-15236200000-test.pdf</span>
            </el-upload>
          </el-form-item>
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="fileMeta.userName"></el-input>
          </el-form-item>
          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="fileMeta.idNumber"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phoneNo">
            <el-input v-model="fileMeta.phoneNo"></el-input>
          </el-form-item>
          <el-form-item label="文件名" prop="fileName">
            <el-input v-model="fileMeta.fileName"></el-input>
          </el-form-item>
          <el-form-item label="文件类型" prop="type">
            <el-select v-model="fileMeta.type" placeholder="文件类型">
              <el-option label="报告" value="report"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="small" icon="el-icon-refresh-right">取 消</el-button>
          <el-button type="primary" icon="el-icon-check" @click="uploadToOSS('fileMeta')" size="small">上传至服务器</el-button>
        </span>
      
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import api from '@/api/file/fileMeta'
export default {
  data() {
    return {
        headerData:{},
      listLoading: true, // 数据是否正在加载
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      searchObj: {}, // 查询表单对象
      fileList:[],
      createTimes: [],
      list:[],
      dialogVisible: false,
      loading:false,
      url:"",
      multipleSelection:[],
      fileMeta:{
          userName:"",
          idNumber:"",
          phoneNo:"",
          fileName:"",
          type:""
      },
      rules: {
                userName: [
                  { required: true, message: '姓名不能为空', trigger: 'blur' },
                  { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
                ],
                idNumber: [
                  { required: true, message: '身份证号不能为空', trigger: 'blur' },
                  { min: 18, max: 18, message: '请检查身份证号是否正确', trigger: 'blur' }
                ],
                phoneNo: [
                  { required: true, message: '手机号不能为空', trigger: 'blur' },
                  { min: 11, max: 11, message: '请检查手机号是否正确', trigger: 'blur' }
                ],
                fileName: [
                  { required: true, message: '文件名不能为空', trigger: 'blur' },
                ],
              
                type: [
                  { required: true, message: '请选择文件类型', trigger: 'blur' }
                ]
              },
      
    }
  },

  // 生命周期函数：内存准备完毕，页面尚未渲染
  created() {
    this.fetchData()

  },


  methods: {
      // uploadFile(option){
      //     let file = option.file
      //     let fileFormData = new FormData();
      //     fileFormData.append("file",file)
      //     fileFormData.append("fileMeta",this.fileMeta)
      //     console.log(fileFormData)
      //     let requestConfig = {
      //           headers: {
      //               'Content-Type': 'multipart/form-data'
      //           },
      //      }
      //     this.$http.post(
      //       "/file/report",
      //       this.fileMeta,
      //       requestConfig
      //     )
          
          
      // },
      openDialog(){
          this.dialogVisible = true
          // this.url = `${window.SITE_CONFIG['apiURL']}/file/report?token=${Cookies.get('token')}`
          this.url = `${window.SITE_CONFIG['apiURL']}/file/fileMeta`
          this.fileList = []
          this.fileMeta = {}
      },
      // -------------
     
      uploadToOSS(fileMeta){
          this.$refs[fileMeta].validate((valid) => {
              if(valid){
                  this.headerData.token=Cookies.get('token')
                  var fileMeta = encodeURIComponent(JSON.stringify(this.fileMeta))
                  this.headerData.fileMeta = fileMeta
                  this.$refs.upload.submit();
                  
              }else{
                  return false
              }
          })
      },
      handleChange(file,fileList){
          const fullName = file.name
          const fileds = fullName.split("-")
          if(fileds && fileds.length == 4){
              this.$set(this.fileMeta,'userName',fileds[0])
              this.$set(this.fileMeta,'idNumber',fileds[1])
              this.$set(this.fileMeta,'phoneNo',fileds[2])
              this.$set(this.fileMeta,'fileName',fileds[3])
          }
          
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，请勿重复提交`);
      }, 
      // 批量删除
      batchRemove() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的记录！')
          return
        }
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 点击确定，远程调用ajax
          // 遍历selection，将id取出放入id列表
          var idList = []
          this.multipleSelection.forEach(item => {
            idList.push(item.id)
          })
          // 调用api
          return api.batchRemove(idList)
        }).then((response) => {
          this.fetchData()
          this.$message.success("删除成功")
        })
      },
      handleSelectionChange(selection) {
        this.multipleSelection = selection
      },
      // 根据id删除数据
      removeDataById(id) {
          
        // debugger
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => { // promise
          // 点击确定，远程调用ajax
          var idList = []
          idList.push(id)
         
          return api.batchRemove(idList)
        }).then((response) => {
          this.fetchData(this.page)
          this.$message.success(response.message || '删除成功')
        }).catch(() => {
           this.$message.info('出现异常，删除失败')
        })
      },
      
   // 上传之前
   beforeUploadHandle (file) {
     if (file.type !== 'application/pdf') {
       this.$message.error("报告类型只支持pdf格式，请检查是否符合要求")
       return false
     }
     return true
   },
   // 上传成功
   successHandle (res, file, fileList) {
     if (res.code !== 0) {
       this.$message.error(res.msg)

     }
     this.$message.success('上传成功')
     this.dialogVisible=false
     this.fetchData()
 
   },
    // 当页码发生改变的时候
    changeSize(size) {
      this.limit = size
      this.fetchData(1)
    },
    searchData(){
      this.loading=true
      this.fetchData()
      this.loading=false
    },
    // 加载banner列表数据
    fetchData(page = 1) {
      this.listLoading=true

      this.page = page

      if(this.createTimes && this.createTimes.length ==2) {
        this.searchObj.createTimeBegin = this.createTimes[0]
        this.searchObj.createTimeEnd = this.createTimes[1]
      }
      this.searchObj.page=this.page
      this.searchObj.limit=this.limit
      api.getPageList(this.searchObj).then(
        response => {
          
          this.list = response.data.data.records
          this.total = parseInt(response.data.data.total)

          // 数据加载并绑定成功
          this.listLoading = false
        }
      )
    },

    // 根据id删除数据
    removeDataById(id) {
      // debugger
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        var idList = []
        idList.push(id)
        return api.batchRemove(idList)
      }).then((response) => {
        this.fetchData(this.page)
        this.$message.success(response.message || '删除成功')
      }).catch(() => {
         this.$message.info('取消删除')
      })
    }

    

  

  }
}
</script>
